<template>
  <view class="page custom-page">
    <custom-head gradient back title="个人信息"> </custom-head>
    <view class="addition">
      <view class="touxiang-box flex col a-center j-c-c">
        <u-upload 
          max-count="1"
          :action="BASE_URL + '/file/upload'" 
          :file-list="fileList" 
          :header="{ Authorization: token }"
          :form-data="{ type: 'avatar' }"
          @on-change="onSuccess"
          @on-remove="omRemove"
          width="140rpx" height="140rpx" 
        >
          <view class="touxiang" slot="addBtn">
            <image src="../../static/img/avatar.png" mode="widthFix"></image>
          </view>
        </u-upload>
        <text>头像</text>
      </view>

      <view class="form">
        <u-form :model="form" ref="uForm" label-width="180">
          <u-form-item label="姓名">
            <u-input v-model="form.name" placeholder="请输入姓名" @click="handleModal('name')" />
            <u-icon name="arrow-right" color="#91959B" size="26"></u-icon>
          </u-form-item>
          <u-form-item label="手机号码">
            <u-input v-model="form.phone" placeholder="请输入电话" @click="handleModal('phone')" />
            <u-icon name="arrow-right" color="#91959B" size="26"></u-icon>
          </u-form-item>
        </u-form>
      </view>

      <u-modal 
        v-model="show" 
        width="600rpx"
        height="800"
        :showCancelButton="true" 
        @confirm="confirm"
        @cancel="cancel"
        :title="showName === 'name'? '修改姓名' : '设置新的手机号码'">
        <u-form :model="form" ref="uForm">
          <view class="bao_name" v-if="showName === 'name'">
						<u-form-item :border-bottom="false" label="姓名" :label-style="{'white-space': 'nowrap','font-size': '30rpx', 'font-weight': 'bold'}" label-width="80">
							<u-input v-model="form.newName" placeholder="请填写您的名字" />
						</u-form-item>
					</view>
          <view class="bao_phone" v-else-if="showName === 'phone'">
            <u-form-item :border-bottom="false" label="手机号码" :label-style="{'white-space': 'nowrap','font-size': '30rpx', 'font-weight': 'bold'}" label-width="140">
							<u-input v-model="form.newPhone" placeholder="请输入新的手机号码" />
						</u-form-item>
            <u-form-item :border-bottom="false" label="验证码" :label-style="{'white-space': 'nowrap','font-size': '30rpx', 'font-weight': 'bold'}" label-width="140">
							<u-input v-model="form.code" placeholder="请输入验证码" />
              <u-button type="primary" :disabled="showBtn" class="text" @click="handleCaptcha">{{buttonText}}</u-button>
						</u-form-item>
          </view>

        </u-form>
      </u-modal>

    </view>
  </view>
</template>

<script>
import { BASE_URL } from '../../api/config';
import { updatetUser, getCode, updatePhone } from '../../api/modules/user';
export default {
  data() {
    return {
      form: {
        name: '',
        phone: '',
        newName: '',
        newPhone: '',
        code: '',
        avatar: '',
      },
      show: false, // 弹出框
      showBtn: false, // 是否禁用按钮
      countdown: 60, // 秒钟
      showName: 'phone', // 默认显示名字
      BASE_URL,
      token: uni.getStorageSync('token'),
      static_uri: getApp().globalData.glb_list.config.static_uri, // 获取全局配置文件
      fileList: [],
    };
  },
  onShow() {
    const { nickname, name, avatar } = JSON.parse(JSON.stringify(getApp().globalData.glbCurrentDataMap));
    this.form.name = nickname
    this.form.phone = name
    this.fileList = [{url: `${this.static_uri}${avatar}`}]
  },
  computed: {
    buttonText: function() {
      return this.showBtn ? `重新获取${this.countdown}` : "获取验证码";
    }
  },
  methods: {
    handleCaptcha() { // 获取验证码
      if (this.showBtn) {
        return;
      }
      console.log('form', this.form)
      const { newPhone } = this.form || {};
      let data = {
        phone:newPhone,
        action: 'regist'
      }

      this._getCode(data)

      this.showBtn = true;
      this.countdown = 60;
      const times = setInterval(() => {
        this.countdown--;
        if (this.countdown === 0) {
          clearInterval(times);
          this.showBtn = false;
        }
      }, 1000)
    }, 
    confirm() { // 确定按钮
      console.log('确定form', this.form)
      console.log('获取 id', this.$route.query.id)
      const { newPhone, code } = this.form
      if (this.showName === 'name') {
        this._updatetUser(this.$route.query.id, {nickname: this.form.newName})
      } else if (this.showName === 'phone') {
        let data = {
          phone: newPhone,
          code
        }
        this._updatePhone(data);
      }
    },
    _updatePhone(data) {
      updatePhone(data).then(res => {
        const { code } = res || {}
        if (code === 201) {
          this.$u.toast('新手机号码设置成功')
          this.form.phone = data.newPhone
        }
      })
    },
    _updatetUser(id, data) {
      updatetUser(id, data).then(res => {
        const { code } = res || {}
        if (code === 201) {
          if (this.showName === 'name') {
            this.$u.toast('修改姓名成功')
          }
          this.form.name = data.newName
        }
        console.log('res ', res)
      })
    },
    _getCode(data) { // 获取验证码
      // //传phone，action:动作名称（eg:regist,login,reset_password)
      // 万能短信 888666
      getCode(data).then(res => {
        const { code, data } = res || {}
        if (code === 200) {
          this.$u.toast(`${data}`)
        }
      })
    },
    cancel() {
      const { nickname, name } = getApp().globalData.glbCurrentDataMap
      this.form = {
        newName: '',
        newPhone: '',
        code: '',
        name: nickname,
        phone: name,
        avatar: this.form.avatar
      }
    },
    handleModal(param) {

      this.showName = param
      this.show = true
    },
    omRemove(index) { // 移除照片
			if (index === 0) {
				this.fileList = []
				this.form.avatar = ''
			}
		},
    onSuccess(data) {  // 照片上传
      const res = JSON.parse(data.data)
      console.log('res-img', res)
      if (res.code == 201) {
        this.form.avatar = res.data.path
        this._updatetUser(this.$route.query.id, { avatar: res.data.path })
      } else {
        this.$refs.uUpload.clear()
        this.$u.toast('上传失败')
      }
    },
  }
};
</script>

<style scoped lang="scss">

.name_content {
  box-sizing: content-box;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 240rpx;
  width: 800rpx;
  /* box-shadow: 0rpx 1rpx 9rpx 0rpx rgba(209,209,209,0.5); */
  border-radius: 11rpx;
  /* padding: 0 41rpx; */
  .Lastname {
    margin-right: 19rpx;
  }
  .input {
    border: 1rpx solid #f1f1f1;
  }
}

.bao_name {
  height: 200rpx;
  .u-form-item {
    padding: 60rpx 41rpx 0;
  }
}

.bao_phone {
  height: 450rpx;
  .u-form-item {
    padding: 60rpx 41rpx 0;
  }
  .text {
      width: 180rpx;
      height: 60rpx;
      font-size: 24rpx;
      padding: 0 10rpx;
  }
}

.touxiang-box {
  padding: 40rpx 0;
  font-size: 30rpx;
}

.touxiang {
  width: 150rpx !important;
  height: 150rpx !important;
  margin: auto;
  border-radius: 50%;
  overflow: hidden;
  margin-bottom: 25rpx;
}

.touxiang image {
  width: 100%;
  height: 100%;
}

.form {
  height: calc(100vh - 386rpx);
  background-color: #fff;
  padding: 0px 45rpx;
  overflow: hidden;
}

.button {
  width: 100%;
  height: 88rpx;
  border-radius: 44rpx;
  margin: 80rpx 0 40rpx 0;
  background-color: #2979ff;
  color: #fff;
  font-size: 32rpx;
  text-align: center;
  line-height: 88rpx;
}

/deep/ .u-form-item--left {
  align-items: self-start !important;
}
</style>
